// 自动驾驶状态实时提示组件 - 基于用户需求说明2.1.5

import React, { useState, useEffect } from 'react';
import { useHmiState } from '../hooks/useHmiState';
import {
  Car,
  AlertTriangle,
  Pause,
  RotateCcw,
  Volume2,
  VolumeX,
  X
} from 'lucide-react';

interface AutonomousStatus {
  id: string;
  type: 'waiting' | 'cruising' | 'lane_change' | 'braking' | 'manual' | 'error';
  title: string;
  message: string;
  icon: React.ReactNode;
  color: string;
  bgColor: string;
  priority: 'low' | 'medium' | 'high' | 'critical';
  timestamp: Date;
  duration?: number;
}

const AutonomousStatusAlert: React.FC = () => {
  const { vehicleStatus } = useHmiState();
  const [currentStatus, setCurrentStatus] = useState<AutonomousStatus | null>(null);
  const [isVisible, setIsVisible] = useState(false);
  const [isMuted, setIsMuted] = useState(false);

  // 生成自动驾驶状态
  const generateAutonomousStatus = (): AutonomousStatus => {
    const statuses: AutonomousStatus[] = [
      {
        id: 'waiting',
        type: 'waiting',
        title: '等待起步',
        message: '车辆已就绪，等待交通信号或前方车辆移动',
        icon: <Pause size={24} />,
        color: 'text-warning-400',
        bgColor: 'bg-warning-600/20 border-warning-500/30',
        priority: 'medium',
        timestamp: new Date(),
        duration: 3000
      },
      {
        id: 'cruising',
        type: 'cruising',
        title: '智驾领航中',
        message: '自动驾驶模式已激活，车辆正在按规划路线行驶',
        icon: <Car size={24} />,
        color: 'text-success-400',
        bgColor: 'bg-success-600/20 border-success-500/30',
        priority: 'low',
        timestamp: new Date(),
        duration: 2000
      },
      {
        id: 'lane_change',
        type: 'lane_change',
        title: '变道中',
        message: '正在执行变道操作，请保持稳定',
        icon: <RotateCcw size={24} />,
        color: 'text-blue-400',
        bgColor: 'bg-blue-600/20 border-blue-500/30',
        priority: 'high',
        timestamp: new Date(),
        duration: 4000
      },
      {
        id: 'braking',
        type: 'braking',
        title: '主动刹车',
        message: '检测到前方障碍物，正在执行主动刹车',
        icon: <AlertTriangle size={24} />,
        color: 'text-danger-400',
        bgColor: 'bg-danger-600/20 border-danger-500/30',
        priority: 'critical',
        timestamp: new Date(),
        duration: 5000
      },
      {
        id: 'manual',
        type: 'manual',
        title: '手动驾驶模式',
        message: '已切换到手动驾驶模式，请安全员接管车辆控制',
        icon: <AlertTriangle size={24} />,
        color: 'text-warning-400',
        bgColor: 'bg-warning-600/20 border-warning-500/30',
        priority: 'high',
        timestamp: new Date(),
        duration: 6000
      }
    ];

    // 根据车辆状态选择合适的状态
    if (vehicleStatus.emergencyStop) {
      return statuses.find(s => s.id === 'braking') || statuses[0];
    }
    
    if (!vehicleStatus.autonomousMode) {
      return statuses.find(s => s.id === 'manual') || statuses[0];
    }

    // 随机选择一个状态（实际应用中应该根据真实车辆状态）
    return statuses[Math.floor(Math.random() * statuses.length)];
  };

  // 语音播报功能
  const speakText = (text: string) => {
    if (isMuted || !('speechSynthesis' in window)) return;
    
    const utterance = new SpeechSynthesisUtterance(text);
    utterance.lang = 'zh-CN';
    utterance.rate = 0.8;
    utterance.pitch = 1;
    speechSynthesis.speak(utterance);
  };

  // 显示状态提示
  const showStatus = (status: AutonomousStatus) => {
    setCurrentStatus(status);
    setIsVisible(true);
    
    // 语音播报
    if (status.priority === 'high' || status.priority === 'critical') {
      speakText(`${status.title}，${status.message}`);
    }

    // 自动隐藏
    if (status.duration) {
      setTimeout(() => {
        setIsVisible(false);
      }, status.duration);
    }
  };

  // 模拟状态变化
  useEffect(() => {
    const interval = setInterval(() => {
      if (vehicleStatus.autonomousMode && !isVisible) {
        const newStatus = generateAutonomousStatus();
        showStatus(newStatus);
      }
    }, 8000); // 每8秒更新一次状态

    return () => clearInterval(interval);
  }, [vehicleStatus.autonomousMode, isVisible]);

  // 手动关闭提示
  const handleClose = () => {
    setIsVisible(false);
    speechSynthesis.cancel(); // 停止语音播报
  };

  // 切换静音
  const toggleMute = () => {
    setIsMuted(!isMuted);
    if (!isMuted) {
      speechSynthesis.cancel();
    }
  };

  if (!isVisible || !currentStatus) {
    return null;
  }

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center pointer-events-none">
      {/* 背景遮罩 */}
      <div className="absolute inset-0 bg-black/30 backdrop-blur-sm" />
      
      {/* 状态提示弹窗 */}
      <div className={`relative max-w-md w-full mx-4 p-6 rounded-xl border-2 ${currentStatus.bgColor} backdrop-blur-md pointer-events-auto animate-in slide-in-from-bottom-4 duration-500`}>
        {/* 关闭按钮 */}
        <button
          onClick={handleClose}
          className="absolute top-4 right-4 p-1 hover:bg-white/10 rounded-full transition-colors"
        >
          <X size={20} className="text-gray-400" />
        </button>

        {/* 静音按钮 */}
        <button
          onClick={toggleMute}
          className="absolute top-4 right-12 p-1 hover:bg-white/10 rounded-full transition-colors"
        >
          {isMuted ? <VolumeX size={20} className="text-gray-400" /> : <Volume2 size={20} className="text-gray-400" />}
        </button>

        {/* 状态内容 */}
        <div className="text-center">
          {/* 图标 */}
          <div className={`mx-auto mb-4 ${currentStatus.color}`}>
            {currentStatus.icon}
          </div>

          {/* 标题 */}
          <h3 className={`text-xl font-bold mb-2 ${currentStatus.color}`}>
            {currentStatus.title}
          </h3>

          {/* 消息 */}
          <p className="text-gray-300 text-sm leading-relaxed">
            {currentStatus.message}
          </p>

          {/* 时间戳 */}
          <div className="mt-4 text-xs text-gray-500">
            {currentStatus.timestamp.toLocaleTimeString('zh-CN')}
          </div>

          {/* 优先级指示器 */}
          <div className="mt-3 flex justify-center">
            <div className={`w-2 h-2 rounded-full ${
              currentStatus.priority === 'critical' ? 'bg-danger-500' :
              currentStatus.priority === 'high' ? 'bg-warning-500' :
              currentStatus.priority === 'medium' ? 'bg-blue-500' :
              'bg-gray-500'
            }`} />
          </div>
        </div>

        {/* 进度条 */}
        {currentStatus.duration && (
          <div className="mt-4 w-full bg-gray-700 rounded-full h-1">
            <div
              className="bg-primary-500 h-1 rounded-full animate-pulse"
              style={{
                animation: `progress ${currentStatus.duration}ms linear forwards`
              }}
            />
          </div>
        )}
      </div>

      {/* 自定义动画样式已移至CSS文件 */}
    </div>
  );
};

export default AutonomousStatusAlert;
